package cn.xo68.boot.auth.server.token.impl;

import cn.xo68.boot.auth.server.domain.OauthRefreshToken;
import cn.xo68.boot.auth.server.domain.OauthUser;
import cn.xo68.boot.auth.server.service.OauthRefreshTokenService;
import cn.xo68.boot.auth.server.service.OauthTokenService;
import cn.xo68.boot.auth.server.token.AbstractTokenRequestCheck;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 密码模式的令牌请求审核
 * @author wuxie
 * @date 2018-8-10
 */
@Component
public class TokenRequestCheckOnRefresToken extends AbstractTokenRequestCheck {

    private static final Logger logger= LoggerFactory.getLogger(TokenRequestCheckOnRefresToken.class);

    @Autowired
    private OauthRefreshTokenService oauthRefreshTokenService;

    @Autowired
    private OauthTokenService oauthTokenService;

    @Override
    public OauthUser checkCredentials() throws OAuthProblemException {
        OauthRefreshToken oauthRefreshToken=oauthRefreshTokenService.get(this.getOAuthTokenRequest().getRefreshToken());
        if(oauthRefreshToken ==null){
            throw OAuthProblemException.error("参数异常","刷新令牌不合法");
        }
        OauthUser oauthUser =getOauthUserService().getByUserId(oauthRefreshToken.getUserId());
        if(oauthUser ==null){
            throw OAuthProblemException.error("参数异常","刷新令牌不合法");
        }
        //清理刷新令牌和旧令牌
        oauthRefreshTokenService.delete(this.getOAuthTokenRequest().getRefreshToken());
        oauthTokenService.delete(oauthRefreshToken.getToken());

        return oauthUser;
    }

}
